package com.jxstjh.conch.handler.handler.impl;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.google.common.base.Throwables;
import com.jxstjh.conch.common.domain.TaskInfo;
import com.jxstjh.conch.common.dto.EmailContentModel;
import com.jxstjh.conch.common.enums.ChannelTypeEnum;
import com.jxstjh.conch.handler.handler.BaseMessageHandler;
import com.jxstjh.conch.handler.handler.MessageHandler;
import com.jxstjh.conch.support.utils.AccountUtil;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 邮件处理器
 */
@Component
@Slf4j
public class EmailHandler extends BaseMessageHandler implements MessageHandler {

    @Autowired
    private AccountUtil accountUtil;

    public EmailHandler() {
        channelCode = ChannelTypeEnum.EMAIL.getCode();
    }

    @Override
    public boolean handler(TaskInfo taskInfo) {

        EmailContentModel emailContentModel = (EmailContentModel) taskInfo.getContentModel();
        MailAccount account = getAccount(taskInfo.getSendAccount());
        try {
            MailUtil.send(account, taskInfo.getReceiver(), emailContentModel.getTitle(), emailContentModel.getContent(), true, null);
        } catch (Exception e) {
            log.error("EmailHandler#handler fail!{},params:{}", Throwables.getStackTraceAsString(e), taskInfo);
            return false;
        }
        return true;
    }

    /**
     * 获取发送邮件账号信息
     */
    private MailAccount getAccount(Integer sendAccount) {

        MailAccount account = accountUtil.getAccount(ChannelTypeEnum.EMAIL.getCodeEn(), sendAccount, new MailAccount());
        try {
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            account.setAuth(true).setStarttlsEnable(true).setSslEnable(true).setCustomProperty("mail.smtp.ssl.socketFactory", sf);
            account.setTimeout(25000).setConnectionTimeout(25000);
        } catch (Exception e) {
            log.error("EmailHandler#getAccount fail!{}", Throwables.getStackTraceAsString(e));
        }
        return account;
    }
}